package com.example.b_308.myapplication.model.base;


import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.b_308.myapplication.comment.OfficeContent;
import com.example.b_308.myapplication.comment.utils.L;
import com.example.b_308.myapplication.model.OfficeResult;
import com.example.b_308.myapplication.comment.net.INetCallBack;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * Created by tongkang on 2017/10/31.
 * 模块基类
 */

public abstract class BaseModel<T extends BaseModel> implements Serializable {

    String URL = "http://10.5.10.113:8080";

    /**
     * 网络请求
     */
    private HttpUtils http = new HttpUtils();

    /**
     * 属性列表
     */
    protected Map<String, Object> attrs;

    public BaseModel() {

        http.configCurrentHttpCacheExpiry(0);
        attrs = new HashMap();
    }

    public BaseModel(String json) {
        http.configCurrentHttpCacheExpiry(0);
        try {
            attrs = JSON.parseObject(json, Map.class);
        } catch (Exception e) {
            L.d("BaseModel","后台返回数据格式出错");
        }
    }

    public BaseModel(BaseModel baseModel) {
        http.configCurrentHttpCacheExpiry(0);
        putAttrs(baseModel);
    }

    /**
     * get方式获取数据
     *
     * @param url          网络地址
     * @param iNetCallBack 网络回调接口
     */
    public void getRequestHttp(String url, final INetCallBack iNetCallBack) {
        http.send(HttpRequest.HttpMethod.GET,
                OfficeContent.URL + url, new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> responseInfo) {
                        OfficeResult officeResult = new OfficeResult(responseInfo.result.toString());
                        iNetCallBack.onNetCallBack(officeResult);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        iNetCallBack.onNetCallBack(
                                new OfficeResult(OfficeContent.FAIL_CODE, OfficeContent.FAIL_REQUEST));
                    }
                });
    }


    protected String paraseUrl(String url, T t) {
        StringBuilder sb = new StringBuilder();
        Map<String, Objects> map = t.getAttrs();
        if (null != map || map.size() != 0) {
            sb.append(url + "?");
            for (Map.Entry<String, Objects> entry : map.entrySet()) {
                sb.append(String.format("%s=%s", entry.getKey(), entry.getValue() + "&"));
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }
        }
        return sb.substring(0, sb.lastIndexOf("&"));
    }


    /**
     * post方式提交数据
     *
     * @param url 网络地址
     */
    public void postData(String url, T t, final INetCallBack iNetCallBack) {
            http.send(HttpRequest.HttpMethod.POST, URL + url, paraseObjToParams(t),
                    new RequestCallBack<Object>() {
                        @Override
                        public void onSuccess(ResponseInfo<Object> responseInfo) {
                            OfficeResult officeResult = new OfficeResult(responseInfo.result.toString());
                            iNetCallBack.onNetCallBack(officeResult);
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            iNetCallBack.onNetCallBack(new OfficeResult(OfficeContent.FAIL_CODE, OfficeContent.FAIL_REQUEST));
                        }
                    });
    }

    private RequestParams paraseObjToParams(T t){
        RequestParams params = new RequestParams("UTF-8");
        Map map = t.getAttrs();
        JSONObject jsonObject = new JSONObject(map);
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toJSONString()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return params;
    }

    public BaseModel(Map attrs) {
        this.attrs = attrs;
    }

    public void setAttrs(Map attrs) {
        this.put("attrs", attrs);
        this.attrs = attrs;
    }

    /**
     * 获取属性
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return attrs.get(key);
    }

    public void put(String key, Object value) {
        attrs.put(key, value);
    }

    public void putAttrs(BaseModel baseModel) {
        if (null != baseModel)
            attrs.putAll(baseModel.getAttrs());
    }

    public String getStr(String key) {
        Object value = attrs.get(key);
        if (null == value)
            return null;
        if (value instanceof String || value instanceof JSONObject)
            return value.toString();
        if (value instanceof JSONArray)
            return ((JSONArray) value).toJSONString();
        return null;
    }

    public String getStr(String key, String defaultValue) {
        Object value = attrs.get(key);
        if (null == value)
            return null;
        if (value instanceof String || value instanceof JSONObject)
            return value.toString();
        if (value instanceof JSONArray)
            return ((JSONArray) value).toJSONString();
        return defaultValue;
    }

    public int getInt(String status) {
        Object value = attrs.get("status");
        if (null == value || !(value instanceof Integer))
            return -1;
        return (int) value;
    }

    public int getInt(String status, int defaultValue) {
        Object value = attrs.get("status");
        if (null == value || !(value instanceof Integer))
            return defaultValue;
        return (int) value;
    }

    public Map getAttrs() {
        return attrs;
    }

    public RequestParams getParams(T t) {
        RequestParams params = new RequestParams();
        params.addHeader("Content-Type", "application/json");
        String json = JSON.toJSONString(t);
        try {
            params.setBodyEntity(new StringEntity(json, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params;
    }



}
